<template>
  <div id="fossiFuel">
    <div class="condition" style="margin: 10px">
      <el-input v-model="listQuery.name" placeholder="请输入燃料名称" style="width: 180px;margin-right: 5px"
                class="filter-item"
      />
      <el-select v-model="listQuery.year" clearable placeholder="请选择年份" style="width: 130px;margin-right: 10px">
        <el-option
          v-for="item in years"
          :key="item"
          :label="item"
          :value="item"
        >
        </el-option>
      </el-select>
      <el-select v-model="listQuery.month" clearable placeholder="请选择月份" style="width: 130px">
        <el-option
          v-for="item in months"
          :key="item"
          :label="item"
          :value="item"
        >
        </el-option>
      </el-select>
      <el-button class="filter-item" type="danger" icon="el-icon-search" @click="searchFossiFuel"
                 style="margin-bottom: 5px;margin-left: 10px"
      >
        查找
      </el-button>

      <el-button class="filter-item" type="danger" icon="el-icon-refresh" @click="clean"
                 style="margin-bottom: 5px;margin-left: 10px"
      >
        清空
      </el-button>

      <el-button class="filter-item" type="danger" icon="el-icon-circle-plus-outline"
                 @click="addFossiFuel"
                 style="margin-bottom: 5px;margin-left: 10px"
      >
        添加燃料燃烧
      </el-button>

      <!--      <el-button class="filter-item" type="danger" icon="el-icon-circle-plus-outline"-->
      <!--                 @click="saveNewFossiFuel"-->
      <!--                 style="margin-bottom: 5px;margin-left: 10px"-->
      <!--      >-->
      <!--        新增燃料-->
      <!--      </el-button>-->

      <el-dialog title="新增化石燃料" :visible.sync="saveNewDialogFormVisible">
        <el-form :model="saveForm" :rules="rules">
          <el-form-item label="化石燃料名称" :label-width="formLabelWidth" prop="name">
            <el-input v-model="saveForm.name" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelSaveNewFossiFuel">取 消</el-button>
          <el-button type="danger" @click="submitSaveNewFossiFuel">确 定</el-button>
        </div>
      </el-dialog>

      <!--   添加燃料   -->
      <el-dialog title="添加燃料" :visible.sync="addDialogFormVisible">
        <el-form :model="addForm" :rules="rules">
          <el-form-item label="燃料名称" :label-width="formLabelWidth" prop="fossiId">
            <el-select v-model="addForm.fossiId" placeholder="请选择燃料" @change="changeMaterial">
              <el-option v-for="(item,index) in fossiFuels" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工序" :label-width="formLabelWidth" prop="processId">
            <el-select v-model="addForm.processId" placeholder="请选择工序">
              <el-option v-for="(item,index) in processList" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="平均低位发热量" :label-width="formLabelWidth" prop="aveFuel">
            <el-input v-model="addForm.aveFuel" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="燃料消耗量" :label-width="formLabelWidth" prop="consumer">
            <el-input v-model="addForm.consumer" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="单位热值含碳量" :label-width="formLabelWidth" prop="carbonFuel">
            <el-input v-model="addForm.carbonFuel" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="碳氧化率" :label-width="formLabelWidth" prop="oxidationRate">
            <el-input v-model="addForm.oxidationRate" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="日期" :label-width="formLabelWidth">
            <el-col :span="11">
              <el-date-picker type="date" placeholder="选择日期"
                              v-model="year"
                              @change="getDate"
                              value-format="yyyy-MM-dd"
                              autocomplete="off"
                              style="width: 100%;"
              >
              </el-date-picker>
            </el-col>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelAddFossiFuel">取 消</el-button>
          <el-button type="danger" @click="submitAddFossiFuel">确 定</el-button>
        </div>
      </el-dialog>

      <!--   编辑燃料   -->
      <el-dialog title="编辑燃料燃烧信息" :visible.sync="editDialogFormVisible">
        <el-form :model="editForm" :rules="rules">
          <el-form-item label="燃料名称" :label-width="formLabelWidth" prop="name">
            <el-input disabled v-model="editForm.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="工序" :label-width="formLabelWidth" prop="product">
            <el-select v-model="editForm.processId" placeholder="请选择工序">
              <el-option v-for="(item,index) in processList" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="平均低位发热量" :label-width="formLabelWidth" prop="aveFuel">
            <el-input v-model="editForm.aveFuel" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="燃料消耗量" :label-width="formLabelWidth" prop="consumer">
            <el-input v-model="editForm.consumer" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="单位热值含碳量" :label-width="formLabelWidth" prop="carbonFuel">
            <el-input v-model="editForm.carbonFuel" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="碳氧化率" :label-width="formLabelWidth" prop="oxidationRate">
            <el-input v-model="editForm.oxidationRate" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="日期" :label-width="formLabelWidth">
            <el-col :span="11">
              <el-date-picker type="date" placeholder="选择日期"
                              v-model="editForm.year"
                              @change="getDate"
                              value-format="yyyy-MM-dd"
                              autocomplete="off"
                              style="width: 150px;"
              >
              </el-date-picker>
            </el-col>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelEditFossiFuel">取 消</el-button>
          <el-button type="danger" @click="submitEditFossiFuel">确 定</el-button>
        </div>
      </el-dialog>


      <el-button class="filter-item" type="danger" icon="el-icon-delete" @click="deleteTagBatch"
                 style="margin-bottom: 5px;margin-left: 10px"
      >
        批量删除
      </el-button>

      <el-button class="filter-item" type="primary" icon="el-icon-download"
                 @click="exportExcel"
                 style="margin-bottom: 5px;margin-left: 10px;margin-top: 5px"
      >
        导出Excel
      </el-button>

      <el-button class="filter-item" type="primary" icon="el-icon-upload2"
                 @click="importExcel"
                 style="margin-bottom: 5px;margin-left: 10px"
      >
        导入数据
      </el-button>

      <el-dialog title="导入" :visible.sync="dialogImportVisible" width="480px">
        <el-form label-position="right" label-width="170px">
          <el-form-item label="文件">
            <el-upload
              :multiple="false"
              :file-list="excel"
              :on-success="onUploadSuccess"
              :action="'http://localhost:39203/carbon/file/importExcel'"
              class="upload-demo">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传xls文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogImportVisible = false">取消</el-button>
        </div>
      </el-dialog>

      <!--      <el-dialog title="导入" :visible.sync="dialogImportVisible" width="480px">-->
      <!--        <el-form label-position="right" label-width="170px">-->
      <!--          <el-form-item label="文件">-->
      <!--            <el-upload-->
      <!--              :multiple="false"-->
      <!--              :on-success="onUploadSuccess"-->
      <!--              action="post"-->
      <!--              @submit="submitImportExcel"-->
      <!--              class="upload-demo"-->
      <!--            >-->
      <!--              <el-button size="small" type="primary">点击上传</el-button>-->
      <!--              <div slot="tip" class="el-upload__tip">只能上传xls文件，且不超过500kb</div>-->
      <!--            </el-upload>-->
      <!--          </el-form-item>-->
      <!--        </el-form>-->
      <!--        <div slot="footer" class="dialog-footer">-->
      <!--          <el-button @click="dialogImportVisible = false">取消</el-button>-->
      <!--        </div>-->
      <!--      </el-dialog>-->

      <el-tooltip class="item" effect="dark" content="刷新" placement="top" style="float: right">
        <!-- span是button的外层标签 -->
        <el-button class="filter-item" type="" icon="el-icon-refresh-left" @click="getList"
                   style="margin-bottom: 5px;margin-left: 10px;"
                   circle
        ></el-button>
      </el-tooltip>

    </div>
    <el-table
      ref="multipleTable"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @sort-change="changeSort"
      :header-cell-class-name="handleHeadAddClass"
    >
      <el-table-column
        type="selection"
        width="55"
      >
      </el-table-column>
      <el-table-column
        prop="id"
        label="序号"
        width="50"
      >
        <template slot-scope="scope">
          {{ scope.$index + 1 + (pageNum - 1) * pageSize }}
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="燃料名称"
        min-width="120"
      >
      </el-table-column>
      <el-table-column
        prop="aveFuel"
        label="平均低位发热量(GJ/t GJ/万m3)"
        min-width="115"
      >
      </el-table-column>
      <el-table-column
        prop="consumer"
        label="消耗量(t)"
        min-width="100"
        :sortable="'custom'"
      >
      </el-table-column>
      <el-table-column
        prop="carbonFuel"
        label="单位热值含碳量(t CO2/GJ)"
        min-width="113"
      >
      </el-table-column>
      <el-table-column
        prop="oxidationRate"
        label="碳氧化率(%)"
        width="100"
      >
      </el-table-column>
      <el-table-column
        prop="activityLevel"
        label="活动水平(GJ)"
        width="100"
      >
      </el-table-column>
      <el-table-column
        prop="emissionFactor"
        label="二氧化碳排放因子(tCO2/t)"
        width="130"
      >
      </el-table-column>
      <el-table-column
        prop="carbonEmission"
        label="CO2排放量(t)"
        width="150"
        :sortable="'custom'"
      >
      </el-table-column>
      <el-table-column
        prop="processName"
        label="工序"
        min-width="150"
      >
      </el-table-column>
      <el-table-column
        prop="year"
        label="年"
        width="80"
        :sortable="'custom'"
      >
      </el-table-column>
      <el-table-column
        prop="month"
        label="月"
        width="59"
        :sortable="'custom'"
      >
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        min-width="150"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--  分页  -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import {showFullScreenLoading, hideFullScreenLoading} from '@/utils/loading'
import {
  addFossiFuel,
  deleteFossiFuel,
  modifyFossiFuel,
  pageList,
  queryAllYears,
  queryFossiFuel, saveNewFossilFuel
} from '@/api/carbon-manage/fossi-fuel'
import {listAllFossiFuel} from '@/api/carbon-manage/material'
import {exportExcel, importExcel} from '@/api/carbon-manage/file'
import {queryProcessByEmissionOrigin} from "@/api/carbon-manage/data";

export default {
  name: 'index',
  data() {
    return {
      months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      years: [],
      year: '',
      excel: [],
      editDate: '',
      listQuery: {
        name: '',
        month: '',
        year: '',
        pageNum: 1,
        pageSize: 10,
        sortArr: []
      },
      tableData: [],
      saveForm: {
        name: '',
        produceStage: 1
      },
      processList: [],
      addForm: {
        fossiId: '',
        processId: '',
        aveFuel: '',
        consumer: '',
        carbonFuel: '',
        oxidationRate: '',
        year: '',
        month: ''
      },
      editForm: {
        id: '',
        processId: '',
        name: '',
        aveFuel: '',
        consumer: '',
        carbonFuel: '',
        oxidationRate: '',
        year: '2022-11-11',
        month: ''
      },
      pageNum: 1,
      pageSize: 10,
      total: 0,

      selectedRowIds: [],

      addDialogFormVisible: false,
      editDialogFormVisible: false,
      saveNewDialogFormVisible: false,
      dialogImportVisible: false,
      formLabelWidth: '140px',
      fossiFuels: [],
      rules: {
        fossiId: [
          {required: true, message: '请选择化石燃料名称', trigger: 'blur'}
        ],
        aveFuel: [
          {required: true, message: '请输入平均热值含碳量', trigger: 'blur'}
        ],
        consumer: [
          {required: true, message: '请输入化石燃料消耗量', trigger: 'blur'}
        ],
        carbonFuel: [
          {required: true, message: '请输入单位热值含碳量', trigger: 'blur'}
        ],
        oxidationRate: [
          {required: true, message: '请输入碳氧化率', trigger: 'blur'}
        ]
      }

    }
  },
  created() {
    this.getList()
    this.getAllYears()
    this.getAllFossiFuel()
  },
  methods: {
    cancelAddFossiFuel() {
      this.addDialogFormVisible = false
    },
    submitImportExcel() {
      importExcel().then(res => {
        console.log(res)
      })
    },
    onUploadSuccess(response, file) {
      this.$message.success('上传成功')
      this.dialogImportVisible = false
      this.excel = []
      this.getList()
    },
    importExcel() {
      this.dialogImportVisible = true
    },
    exportExcel() {
      // window.open('http://localhost:39203/file/exportExcel')
      this.$confirm('确定导出吗', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
        callback: (action) => {
          if (action === 'confirm') {
            exportExcel('fossilFuel').then(response => {
              const contentType = response.type
              if (contentType === 'application/vnd.ms-excel') {
                let blob = new Blob([response], {type: 'application/vnd.ms-excel'})
                let url = window.URL.createObjectURL(blob)
                const link = document.createElement('a') // 创建a标签
                link.href = url
                link.download = '燃料燃烧碳排放数据.xlsx'
                link.click()
                URL.revokeObjectURL(url) // 释放内存
                this.$message.success('导出成功')
                return
              }
              this.$message.error('导出失败')
            })
          }
        }
      })
    },
    submitSaveNewFossiFuel() {
      saveNewFossilFuel(this.saveForm).then(res => {
        this.$message.success('化石燃料新增成功')
        this.saveNewDialogFormVisible = false
        this.editForm.name = ''
      })
    },
    cancelSaveNewFossiFuel() {
      this.saveNewDialogFormVisible = false
      this.saveForm.name = ''
    },
    getAllFossiFuel() {
      listAllFossiFuel().then(res => {
        this.fossiFuels = res.data
      })
    },
    saveNewFossiFuel() {
      this.saveNewDialogFormVisible = true
    },
    getDate(t) {
      let split = t.split('-')
      this.addForm.year = parseInt(split[0])
      this.addForm.month = parseInt(split[1])
    },
    getAllYears() {
      queryAllYears().then(res => {
        this.years = res.data
      })
    },
    handleHeadAddClass({column}) {
      this.listQuery.sortArr.forEach(item => {
        if (item.prop === column.property) {
          column.order = item.order
        }
      })
    },
    changeSort(column, prop, order) {
      if (column.prop) {
        if (this.listQuery.sortArr.length > 0) {
          this.listQuery.sortArr.forEach((item, index) => {
            if (item.prop === column.prop) {
              this.listQuery.sortArr[index].order = column.order
            }
            let a = this.listQuery.sortArr.some(item => {
              return item.prop === column.prop
            })
            if (!a) {
              this.listQuery.sortArr.push({
                prop: column.prop,
                order: column.order
              })
            }
          })
        } else {
          this.listQuery.sortArr.push({
            prop: column.prop,
            order: column.order
          })
        }
      }
      console.log(this.listQuery.sortArr)
      this.getList()//请求后端获取数据，this.queryParams.sortArr为放多列排序数据的参数，格式为[{prop: 'ptState',order:'descending'}]
    },
    clean() {
      this.listQuery.name = ''
      this.listQuery.year = ''
      this.listQuery.month = ''
    },
    deleteTagBatch() {
      let ids = this.selectedRowIds
      if (ids === null || ids.length === 0) {
        this.$message.error('请选择要删除的燃料')
        return
      }
      this.$confirm('此操作将永久删除这些燃料, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFossiFuel(ids).then(res => {
          this.getList()
          this.$message.success('批量删除成功')
        })
      }).catch(() => {
      })
    },
    submitAddFossiFuel() {
      console.log(this.addForm)
      if (this.addForm.fossiId === '' ||
        this.addForm.aveFuel === '' || this.addForm.carbonFuel === '' ||
        this.addForm.consumer === '' || this.addForm.oxidationRate === '') {
        return
      }
      addFossiFuel(this.addForm).then(res => {
        this.addDialogFormVisible = false
        this.getList()
        this.$message.success('燃料添加成功')
      })
    },
    cancelEditFossiFuel() {
      this.editDialogFormVisible = false
      this.editForm = {}
    },
    submitEditFossiFuel() {
      let form = this.editForm
      if (form.aveFuel === '' || form.consumer === '' ||
        form.carbonFuel === '' || form.oxidationRate === '') {
        return
      }
      var split = this.editForm.year.split('-')
      this.editForm.year = split[0]
      this.editForm.month = split[1]
      modifyFossiFuel(this.editForm).then(res => {
        this.$message.success('燃料燃烧记录更新成功')
        this.editDialogFormVisible = false
        this.getList()
      })
    },
    addFossiFuel() {
      this.addDialogFormVisible = true
    },
    handleEdit(index, row) {
      queryProcessByEmissionOrigin(row.fossiId).then(res => {
        this.processList = res.data;
        console.log(res.data)
      })
      this.editForm.processId = row.processId;
      this.editForm.id = row.id
      this.editForm.name = row.name
      this.editForm.aveFuel = row.aveFuel
      this.editForm.consumer = row.consumer
      this.editForm.carbonFuel = row.carbonFuel
      this.editForm.oxidationRate = row.oxidationRate
      this.editForm.year = row.year + '-' + row.month + '-1'
      this.editDialogFormVisible = true
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = [row.id]
        deleteFossiFuel(ids).then(res => {
          this.getList()
          this.$message.success('标签删除成功')
        })
      }).catch(() => {
      })
    },
    searchFossiFuel() {
      this.getList()
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getList()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.getList()
    },
    getList() {
      showFullScreenLoading()
      setTimeout(() => {
        this.listQuery.pageNum = this.pageNum
        this.listQuery.pageSize = this.pageSize
        pageList(this.listQuery).then(res => {
          let data = res.data
          this.tableData = data.rows
          this.total = parseInt(data.total)
          hideFullScreenLoading()
        }).catch(() => {
          hideFullScreenLoading()
        })
      }, 100)

    },
    handleSelectionChange(val) {
      this.selectedRowIds = this.$refs.multipleTable.selection.map((item) => item.id)
    },
    changeMaterial(id) {
      queryProcessByEmissionOrigin(id).then(res => {
        this.processList = res.data
      })
    },
  }
}
</script>

<style scoped>

</style>
